package com.feihong.txgw.ui.activity.user;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.amap.api.services.core.PoiItem;
import com.blankj.utilcode.util.RegexUtils;
import com.feihong.txgw.R;
import com.feihong.txgw.inter.contract.adr.IDeliveryAdrEditContract;
import com.feihong.txgw.message.DeliveryAdrChangeMessage;
import com.feihong.txgw.message.DelvieryAdrSelectMessage;
import com.feihong.txgw.message.LoginMessage;
import com.feihong.txgw.model.base_bean.BaseResponse;
import com.feihong.txgw.model.bean.deliveryAdr.AdressSelectMapPoiInfoEntity;
import com.feihong.txgw.model.bean.deliveryAdr.DeliveryAdrEntity;
import com.feihong.txgw.tx_precenter.EditDeliveryAdrMainPrecenter;
import com.feihong.txgw.ui.mvp.BaseMVPCompateActivity;
import com.feihong.txgw.ui.mvp.precenter.AbBasePrecenter;
import com.feihong.txgw.utils.adress.StringEmpty;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;


/**
 * @author wangziheng
 * @name txgw_app
 * @class name：com.feihong.txgw.ui.activity.user
 * @class describe:  修改、添加收货地址
 * @time 2017/7/4 19:18
 * @change
 * @chang time
 * @class describe
 */
public class MyDeliveryAdrEditActivity extends BaseMVPCompateActivity<IDeliveryAdrEditContract.AbDeliveryAdrEditMainPrecenter> implements View.OnClickListener, IDeliveryAdrEditContract.IDeliveryAdrEditMainView {
    /**
     * 收货人姓名
     */
    @BindView(R.id.delivery_adr_addedit_contact_name)
    EditText mDeliveryAdrContactName;
    /**
     * 收货人电话
     */
    @BindView(R.id.delivery_adr_contact_phone)
    EditText mDeliveryAdrContactPhone;
    /**
     * 地区
     */
    @BindView(R.id.delivery_adr_addedit_province)
    TextView mDeliveryProvinceAdr;
    /**
     * 详细地址
     */
    @BindView(R.id.delivery_adr_addedit_adress)
    EditText mDeliveryAdrAdress;
    /**
     * 收货人性别
     */
    @BindView(R.id.delivery_adr_addedit_select_man)
    ImageView mDeliveryAdrSexMan;
    @BindView(R.id.delivery_adr_addedit_select_gril)
    ImageView mDeliveryAdrSexGril;
    /**
     * 设置默认状态
     */
    @BindView(R.id.delivery_adr_addedit_set_commendUse)
    ImageView mDeliverySettingOpenStatus;
    @BindView(R.id.savaAdrInfo)
    TextView mDeliverySaveInfo;

    /**
     * 标题返回
     */
    @BindView(R.id.btn_back)
    ImageView mEditBtn;
    /**
     * 标题名称
     */
    @BindView(R.id.txt_pagetitle)
    TextView mAdrTitle;
    @BindView(R.id.top_back_layout)
    RelativeLayout mTopLayout;
    /**
     * 地址信息
     */
    private DeliveryAdrEntity mDeliveryAdrEntity;
    /**
     * 用户性别
     */
    private boolean isMan = true;
    /**
     * 是否设置为默认地址
     */
    private boolean isClose = true;
    private Intent mIntent;

    private Drawable mSexSelect, mSexUnselect;
    private Drawable mSettingOpen, mSettingClose;
    /**
     * 加载动画
     */
    @BindView(R.id.lay_loading)
    RelativeLayout mLoadLayout;
    /**
     * 加载提示文字
     */
    @BindView(R.id.lay_loading_txt)
    TextView mLoadText;
    /**
     * 0  添加收货地址   1  修改收货地址
     */
    private String adrType;
    /**
     * 详细地址
     */
    private String mDetailAdr;

    /**
     * 包含locationInfo信息的实体类
     */
    private AdressSelectMapPoiInfoEntity mAdressSelectMapPoiInfoEntity;
    /**
     * locationInfo引用
     */
    private String mMapPoiLocationInfo;

    @Override
    public void setTheme() {

    }

    @Override
    public int setLayoutID() {
        return R.layout.activity_delivery_adr_edit_layout;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        EventBus.getDefault().register(this);
        mLoadLayout.setVisibility(View.GONE);
        mAdrTitle.setTextColor(getResources().getColor(R.color.black_text));
        mIntent = getIntent();
    }

    @Override
    public void bindData() {

        mAdressSelectMapPoiInfoEntity = new AdressSelectMapPoiInfoEntity();
        mSexSelect = getResources().getDrawable(R.mipmap.delivery_adr_sex_select);
        mSexUnselect = getResources().getDrawable(R.mipmap.delivery_adr_sex_unselect);
        mSettingClose = getResources().getDrawable(R.mipmap.delivery_adr_setting_close);
        mSettingOpen = getResources().getDrawable(R.mipmap.delivery_adr_setting_open);

        if (mIntent != null) {
            Bundle bundle = mIntent.getExtras();
            if (bundle != null) {
                /**
                 * adr_type   0 添加地址  1  修改地址
                 */
                adrType = bundle.getString("type");
                if ("0".equals(adrType)) {
                    mAdrTitle.setText(getResources().getString(R.string.delivery_adr_add_title));
                } else {
                    mAdrTitle.setText(getResources().getString(R.string.delivery_adr_edit_title));
                }
                mDeliveryAdrEntity = bundle.getParcelable("adressInfo");
                /**
                 * 如果是修改地址 则将传过来的收货地址信息展示在界面上
                 */
                if (mDeliveryAdrEntity != null) {
                    mAdress = (StringEmpty.isEmpty(mDeliveryAdrEntity.getAddress()) ? "" : mDeliveryAdrEntity.getAddress());
                    mMapPoiLocationInfo = mDeliveryAdrEntity.getLocation_info();
                    mCityID = mDeliveryAdrEntity.getCitycode();
                    mDeliveryAdrContactName.setText(mDeliveryAdrEntity.getConsignee());
                    mDeliveryAdrContactPhone.setText(mDeliveryAdrEntity.getMobile());
                    if ("1".equals(mDeliveryAdrEntity.getGender())) {
                        isMan = true;
                        mDeliveryAdrSexMan.setImageDrawable(mSexSelect);
                        mDeliveryAdrSexGril.setImageDrawable(mSexUnselect);
                    } else {
                        isMan = false;
                        mDeliveryAdrSexGril.setImageDrawable(mSexSelect);
                        mDeliveryAdrSexMan.setImageDrawable(mSexUnselect);
                    }

//                    provinceName = mDeliveryAdrEntity.getSheng();
//                    provinceId = mDeliveryAdrEntity.getSheng_id();
//                    cityName = mDeliveryAdrEntity.getShi();
//                    cityId = mDeliveryAdrEntity.getShi_id();
//                    countyId = mDeliveryAdrEntity.getQu_id();
//                    countyName = mDeliveryAdrEntity.getQu();
//                    if (TextUtils.isEmpty(provinceName)) {
//                        provinceName = "";
//                    }
//                    if (TextUtils.isEmpty(cityName)) {
//                        cityName = "";
//                    }
//                    if (TextUtils.isEmpty(countyName)) {
//                        countyName = "";
//                    }
                    // 如果是以前新增的地址进行修改
                    if (StringEmpty.isEmpty(mMapPoiLocationInfo)) {
                        mDeliveryProvinceAdr.setText(null);
                    } else {
                        try {
                            JSONObject jsonObject = new JSONObject(mMapPoiLocationInfo);
                            String adrName = jsonObject.optString("name");
                            mDeliveryProvinceAdr.setText(StringEmpty.isEmpty(adrName) ? null : adrName);
                            mAdressSelectMapPoiInfoEntity.setName(StringEmpty.isEmpty(mDeliveryAdrEntity.getAddress()) ? null : mDeliveryAdrEntity.getAddress());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    mDeliveryAdrAdress.setText(TextUtils.isEmpty(mDeliveryAdrEntity.getHouse_num()) ? "" : mDeliveryAdrEntity.getHouse_num());
                    if ("1".equals(mDeliveryAdrEntity.getIs_default())) {
                        isClose = false;
                        mDeliverySettingOpenStatus.setImageDrawable(mSettingOpen);
                    } else {
                        isClose = true;
                        mDeliverySettingOpenStatus.setImageDrawable(mSettingClose);
                    }
                } else
                /**
                 * 如果是添加新地址  则新建集合
                 */ {
                    mDeliveryAdrEntity = new DeliveryAdrEntity();
                }
            }
        }
        mDeliveryAdrSexMan.setOnClickListener(this);
        mDeliveryAdrSexGril.setOnClickListener(this);
        mDeliverySettingOpenStatus.setOnClickListener(this);
        mDeliverySaveInfo.setOnClickListener(this);
        mEditBtn.setOnClickListener(this);
        mDeliveryProvinceAdr.setOnClickListener(this);

    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {

    }

    private String AdrErrorMsg;
    private String AdrSuccessMsg;

    @Override
    public void onClick(final View view) {
        switch (view.getId()) {
            case R.id.delivery_adr_addedit_province:
                Intent intent = new Intent(this, MapAddressActivity.class);
                startActivity(intent);
                break;
            case R.id.delivery_adr_addedit_select_man:
                mDeliveryAdrSexMan.setImageDrawable(mSexSelect);
                isMan = true;
                mDeliveryAdrSexGril.setImageDrawable(mSexUnselect);
                break;
            case R.id.delivery_adr_addedit_select_gril:
                mDeliveryAdrSexMan.setImageDrawable(mSexUnselect);
                isMan = false;
                mDeliveryAdrSexGril.setImageDrawable(mSexSelect);
                break;
            case R.id.delivery_adr_addedit_set_commendUse:
                if (isClose) {
                    isClose = !isClose;
                    mDeliverySettingOpenStatus.setImageDrawable(mSettingOpen);
                } else {
                    isClose = !isClose;
                    mDeliverySettingOpenStatus.setImageDrawable(mSettingClose);
                }
                break;
            case R.id.savaAdrInfo:
                if (isClose) {
                    mDeliveryAdrEntity.setIs_default("0");
                } else {
                    mDeliveryAdrEntity.setIs_default("1");
                }
                if (isMan) {
                    mDeliveryAdrEntity.setGender("1");
                } else {
                    mDeliveryAdrEntity.setGender("2");
                }
                if (TextUtils.isEmpty(mDeliveryAdrContactName.getText())) {
                    showSystemToast("请填写收货人姓名");
                    return;
                }
                if (TextUtils.isEmpty(mDeliveryAdrContactPhone.getText())) {
                    showSystemToast("请填写收货人电话");
                    return;
                }
                if (!RegexUtils.isMobileExact(mDeliveryAdrContactPhone.getText())) {
                    showSystemToast("手机号格式不正确");
                    return;
                }
                if (TextUtils.isEmpty(mDeliveryProvinceAdr.getText())) {
                    showSystemToast("请选择地区");
                    return;
                }
                mDetailAdr = mDeliveryAdrAdress.getText().toString();
                if (TextUtils.isEmpty(mDetailAdr)) {
                    showSystemToast("请填写详细地址");
                    return;
                }
                if (isFastDoubleClick()) {
                    return;
                }
                if (TextUtils.isEmpty(mMapPoiLocationInfo)) {
                    mAdressSelectMapPoiInfoEntity.setAddress(mAdress);
                    mMapPoiLocationInfo = JSON.toJSONString(mAdressSelectMapPoiInfoEntity);
                }
                mDeliverySaveInfo.setClickable(false);
                mLoadLayout.setVisibility(View.VISIBLE);
                mLoadText.setText(getResources().getString(R.string.delivery_adr_submit_status));
                ;
                if ("0".equals(adrType)) {
                    mDeliveryAdrEntity.setAddr_id("0");
                    AdrErrorMsg = getResources().getString(R.string.delivery_adr_add_error);
                    AdrSuccessMsg = "添加地址成功";
                } else {
                    AdrErrorMsg = getResources().getString(R.string.delivery_adr_edit_error);
                    AdrSuccessMsg = "修改地址成功";
                }
                mDeliveryAdrEntity.setMobile(mDeliveryAdrContactPhone.getText().toString());
                mDeliveryAdrEntity.setConsignee(mDeliveryAdrContactName.getText().toString());
                // 如果详细地址没有  则不加入请求参数
                if (TextUtils.isEmpty(mDetailAdr)) {
                    mDeliveryAdrEntity.setAddress(mDeliveryProvinceAdr.getText().toString());
                } else {
                    mDeliveryAdrEntity.setAddress(mDeliveryProvinceAdr.getText().toString() + ">" + mDeliveryAdrAdress.getText().toString());
                }
                mDeliveryAdrEntity.setCitycode(mCityID);
                mPresenter.editAdr(mMapPoiLocationInfo, mDeliveryAdrEntity);
                break;
            case R.id.btn_back:
                if (mLoadLayout != null && mLoadLayout.getVisibility() == View.VISIBLE) {
                    return;
                }
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    public void onBackPressedSupport() {
        if (mLoadLayout != null && mLoadLayout.getVisibility() == View.VISIBLE) {
            mLoadLayout.setVisibility(View.GONE);
            return;
        }
        super.onBackPressedSupport();
    }

    private static long lastClickTime;

    private static boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        if (0 < timeD && timeD < 1000 * 2) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    /**
     * 用户选择的地址的省市区街道名称拼接
     */
    private String mAdress;
    /**
     * 城市id
     */
    private String mCityID;

    /**
     * 从高德地图选择地理位置后的监听回调
     *
     * @param delvieryAdrSelectMessage
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void querySelectMapPoi(DelvieryAdrSelectMessage delvieryAdrSelectMessage) {
        mMapPoiLocationInfo = null;
        PoiItem poiItem = delvieryAdrSelectMessage.getPoiItem();
        mDeliveryProvinceAdr.setText(poiItem.getAdName() + poiItem.toString());
        mAdressSelectMapPoiInfoEntity.setName(poiItem.getAdName() + poiItem.toString());
        mAdressSelectMapPoiInfoEntity.setLatitude(String.valueOf(poiItem.getLatLonPoint().getLatitude()));
        mAdressSelectMapPoiInfoEntity.setLongitude(String.valueOf(poiItem.getLatLonPoint().getLongitude()));
        mAdressSelectMapPoiInfoEntity.setRegionName(poiItem.getAdName());
        mAdressSelectMapPoiInfoEntity.setAdcode(poiItem.getAdCode());
        mAdress = poiItem.getProvinceName() + poiItem.getCityName() + poiItem.getAdName() + poiItem.getSnippet();
        mCityID = poiItem.getCityCode();
    }

    @Override
    public void editAdrResult(BaseResponse result) {
        mLoadLayout.setVisibility(View.GONE);
        if (200 == result.code) {
            showDialog(null, AdrSuccessMsg, new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialogInterface) {
                    EventBus.getDefault().post(new DeliveryAdrChangeMessage());
                    finish();
                }
            });
        } else {
            showDialog(null, AdrErrorMsg);
        }
    }

    @Override
    public void loadDataComplated() {

    }

    @Override
    public void loadDataError() {
        mDeliverySaveInfo.setClickable(true);
        showDialog(null, getResources().getString(R.string.connect_service_error));
        mLoadLayout.setVisibility(View.GONE);
    }

    @NonNull
    @Override
    public AbBasePrecenter initPresenter() {
        return EditDeliveryAdrMainPrecenter.create();
    }
}
